package cn.lingnan.controller.user;

import cn.lingnan.pojo.dto.UserLoginDTO;
import cn.lingnan.pojo.dto.UserRegisterDTO;
import cn.lingnan.pojo.entity.User;
import cn.lingnan.pojo.vo.UserLoginVO;
import cn.lingnan.service.LoginService;
import cn.lingnan.utils.JwtUtils;
import cn.lingnan.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class LoginController {
    @Autowired
  private LoginService loginService;

   @PostMapping("/login")
   @CrossOrigin
   public Result<UserLoginVO> userLogin(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登陆:{}", userLoginDTO);
     User user= loginService.userLogin(userLoginDTO);
     if(user==null){
         return Result.error("用户名或密码错误");
     }
     if(user.getStatus()==0){
         return Result.error("用户已被禁用");
     }
     log.info("用户登陆成功:{}", user);

       //登录成功后，生成jwt令牌

           //生成jwt令牌
           Map<String, Object> claims=new HashMap<>();
           claims.put("id",user.getUserId());
           claims.put("username",user.getUserName());
           String jwt=  JwtUtils.generateJwt(claims);

  UserLoginVO userLoginVO= UserLoginVO.builder()
           .userId(user.getUserId())
           .userName(user.getUserName())
           .phoneNumber(user.getPhoneNumber())
           .avatar(user.getAvatar())
           .token(jwt)
           .build();

     return Result.success(userLoginVO);
   }

   @PutMapping("/register")
   @CrossOrigin
   public Result userRegister(@RequestBody UserRegisterDTO userRegisterDTO){
       log.info("用户注册:{}", userRegisterDTO);
       loginService.userRegister(userRegisterDTO);
       log.info("用户注册成功");
    return Result.success();
   }
}
